<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
    <div class="min-h-screen bg-gray-50 relative">
        <div v-show="showLoading"
             class="fixed inset-0 bg-gray-900/50 backdrop-blur-sm flex items-center justify-center z-50">
            <div class="bg-white rounded-lg p-8 flex flex-col items-center">
                <div class="w-16 h-16 border-4 border-blue-600 border-t-transparent rounded-full animate-spin mb-4">
                </div>
                <p class="text-lg font-medium text-gray-800">AI 智能分析中...</p>
                <p class="text-sm text-gray-500 mt-2">正在为您匹配最佳话术</p>
            </div>
        </div>
        <!-- 顶部导航 -->
        <nav class="bg-white shadow-sm">
            <div class="max-w-7xl mx-auto px-4 h-16 flex items-center">
                <h1 class="flex-1 text-center">
					<span
                        class="text-xl font-bold bg-gradient-to-r from-blue-600 to-blue-800 bg-clip-text text-transparent">JBoltAI智能话术助手</span>
                    <span class="text-sm font-medium text-gray-400 ml-2">AI Script Assistant</span>
                </h1>
            </div>
        </nav>
        <div class="max-w-7xl mx-auto px-4 py-8">
            <!-- 搜索区域 -->
            <div class="mb-8">
                <div class="relative flex">
                    <div class="relative flex-1">
                        <input type="text" v-model="searchQuery" @keyup.enter="handleShowLoading"
                               class="w-full h-12 pl-12 pr-4 text-gray-700 placeholder-gray-400 border border-gray-200 rounded-l-lg focus:outline-none focus:border-blue-500 transition-all duration-300 focus:shadow-lg focus:ring-2 focus:ring-blue-200"
                               placeholder="输入客户问题，智能匹配最佳话术"/>
                        <i class="fas fa-search absolute left-4 top-4 text-gray-400"></i>
                    </div>
                    <button @click="handleShowLoading"
                            class="h-12 px-8 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white font-medium rounded-r-lg flex items-center justify-center transition-all duration-300 hover:shadow-lg hover:scale-[1.02] !rounded-button whitespace-nowrap">
                        <i class="fas fa-robot mr-2"></i>
                        智能提问
                    </button>
                </div>
                <div class="mt-4 flex flex-wrap gap-2">
                    <button v-for="(question, index) in exampleQuestions" :key="index"
                            @click="searchQuery = question.content"
                            class="px-3 py-1 text-sm bg-gray-100 text-gray-600 rounded-full hover:bg-blue-100 hover:text-blue-600 transition-colors duration-300 !rounded-button whitespace-nowrap">
                        {{ question.content }}
                    </button>
                </div>
            </div>
            <div class="flex flex-col gap-8">
                <!-- AI 智能推荐 -->
                <div class="bg-white rounded-lg shadow-sm p-6" v-if="answerShow">
                    <h2 class="text-lg font-medium mb-4">AI 智能回答</h2>
                    <div class="p-4 border border-blue-100 rounded-lg bg-blue-50">
                        <div class="flex items-start mb-3">
                            <i class="fas fa-robot text-blue-600 mt-1"></i>
                            <div class="ml-3">
                                <h3 class="font-medium text-blue-800">最佳回答建议</h3>
                                <p class="mt-2 text-gray-700 leading-relaxed" v-html="md.render(aiAnswer)">

                                </p>
                            </div>
                        </div>
                        <div
                            class="flex items-center justify-between text-sm text-gray-500 mt-2 pt-2 border-t border-blue-200">
                            <div class="flex items-center space-x-4">
                                <span><i class="fas fa-thumbs-up mr-1"></i>98% 相关度</span>
                                <span><i class="fas fa-chart-line mr-1"></i>95% 转化率</span>
                            </div>
                            <button
                                class="text-blue-600 hover:text-blue-700 transition-transform duration-300 hover:scale-110 !rounded-button whitespace-nowrap"
                                @click="copyScript(aiAnswer)">
                                <i class="fas fa-copy mr-1"></i>复制回答
                            </button>
                        </div>
                    </div>
                </div>
                <!-- 话术推荐和统计区域 -->
                <div class="grid grid-cols-12 gap-8">
                    <div class="col-span-12">
                        <!-- 话术推荐 -->
                        <div class="bg-white rounded-lg shadow-sm p-6 mb-6" v-if="fileShow">
                            <h2 class="text-lg font-medium mb-4">相关推荐话术</h2>
                            <div class="space-y-4">
                                <div v-for="(script, index) in recommendedScripts" :key="index"
                                     class="p-4 border border-gray-100 rounded-lg hover:border-blue-100 hover:shadow-md hover:bg-blue-50/30 transition-all duration-300">
                                    <div class="flex justify-between items-start">
                                        <div class="flex-1">
                                            <h3 class="text-base font-medium text-gray-900 mb-2">
                                                {{ script.title }}
                                            </h3>
                                            <p class="text-gray-600">{{ script.content }}</p>
                                            <p class="text-gray-600" style="font-weight: 600;">来自&nbsp;
                                                <{{ script.fileName }}>
                                            </p>
                                        </div>
                                        <div class="flex items-center space-x-2 ml-4">
                                            <button
                                                class="p-2 text-gray-400 hover:text-blue-600 transition-transform duration-300 hover:scale-125 !rounded-button whitespace-nowrap"
                                                @click="copyScript(script.content)">
                                                <i class="fas fa-copy"></i>
                                            </button>
                                            <button
                                                class="p-2 text-gray-400 hover:text-blue-600 transition-transform duration-300 hover:scale-125 !rounded-button whitespace-nowrap"
                                                @click="toggleLike(script)">
                                                <i class="fas fa-star"
                                                   :class="{ 'text-yellow-500': script.isLiked }"></i>
                                            </button>
                                        </div>
                                    </div>
                                    <div class="mt-2 flex items-center text-sm text-gray-500">
										<span class="mr-4">
											<i class="fas fa-thumbs-up mr-1"></i>
											{{ script.likes }}
										</span>
                                        <span>
											<i class="fas fa-eye mr-1"></i>
											{{ script.views }}
										</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- 使用统计 -->
                        <div class="bg-white rounded-lg shadow-sm p-6">
                            <h2 class="text-lg font-medium mb-4">话术使用统计</h2>
                            <div ref="chartRef" class="w-full h-80"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script setup>
import {ref, onMounted, watch, onBeforeUnmount} from 'vue';
import * as echarts from 'echarts';
import {useMessage} from 'naive-ui'
import {JBoltApi} from "@/service/request/index.js";
import {useWebSocketStore} from "@/stores/websocket.js";
import AiChat from '@/components/_builtin/jb-ai-chat/index.js'
import {storeToRefs} from "pinia";
import markdownit from "markdown-it";

//-------变量
const message = useMessage()
const aiAnswer = ref("")
const chatInstance = ref(null);
const webSocketStore = storeToRefs(useWebSocketStore())
const fileShow = ref(false)
const answerShow = ref(false)
const session = ref(null);
const searchQuery = ref('');
const showLoading = ref(false);
const exampleQuestions = ref();
const selectedCategory = ref('常见问题');
const categories = [];
const recommendedScripts = ref([]);
const selectCategory = (category) => {
    selectedCategory.value = category;
};
const md = markdownit({
    html: true,
    breaks: true,
    linkify: true,
    typographer: true
});

//监听事件
watch(() => webSocketStore.ws.value, () => {
    console.debug("websock重连")
    if (chatInstance.value) {
        chatInstance.value.updateWebSocket(webSocketStore.ws.value)
    }
})


//获取默认的提问
function getQuestion() {
    JBoltApi.get(`/aiSmartTalk/getDefaultQuestion/${import.meta.env.VITE_KLB_ID}`).then((res) => {
        let list = res.result.data;
        if (list != null && list.length > 0) {
            exampleQuestions.value = list;

        }
    });
}


//1. 到.env配置文件中，配置该demo的appId
//2. 进入页面的时候，创建一个会话
function addSession() {
    JBoltApi.post('/aiAppSession/add', {
        name: '新的智能能话术助手Demo会话',
        appId: import.meta.env.VITE_APP_ID,
    }).then((res) => {
        session.value = res.result.data;

        initWebsocket();
    });
}


//3. 初始化websocket
function initWebsocket() {
    chatInstance.value = new AiChat(null, {
        websocketInstance: webSocketStore.ws.value,
        app: import.meta.env.VITE_APP_ID,
        sessionId: session.value.id,
        global: null,
        onMsgSend: (msg) => {
        },
        onMsgReceive: (msg) => {
            if (msg.action == 'response') {
                showLoading.value = false;
                answerShow.value = true;
                aiAnswer.value = aiAnswer.value+msg.data.content.text;
            } else if (msg.action == 'reference') {
                fileShow.value = true;
                let list = msg.data;
                list.forEach((item, index) => {
                    let data = {
                        title: item.content.split("\n")[0],
                        content: item.content.split("\n")[1],
                        likes: 286,
                        views: 1254,
                        fileName: item.fileName,
                        isLiked: false
                    }
                    recommendedScripts.value.push(data);
                });
            }
        },
    })
}

//初始化图标
function initEchars() {
    const chartDom = document.querySelector('.h-80');
    const myChart = echarts.init(chartDom);
    const option = {
        animation: false,
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['使用次数', '好评率']
        },
        xAxis: {
            type: 'category',
            data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        },
        yAxis: [
            {
                type: 'value',
                name: '使用次数',
                min: 0,
                max: 250
            },
            {
                type: 'value',
                name: '好评率',
                min: 0,
                max: 100,
                axisLabel: {
                    formatter: '{value}%'
                }
            }
        ],
        series: [
            {
                name: '使用次数',
                type: 'bar',
                data: [120, 180, 150, 203, 190, 230, 165]
            },
            {
                name: '好评率',
                type: 'line',
                yAxisIndex: 1,
                data: [85, 92, 88, 95, 89, 93, 87]
            }
        ]
    };
    myChart.setOption(option);
}


const handleShowLoading = () => {
    if (searchQuery.value.trim() === '') {
        message.error('请输入客户的问题,才能给您匹配最佳的话术哦');
        return;

    }
    showLoading.value = true;
    fileShow.value = false;
    answerShow.value = false;
    chatInstance.value.sendMessage({
        action: 'request',
        data: {
            role: "user",
            content: {"text": searchQuery.value.trim()}
        }
    });
};

const copyScript = async (content) => {
    const textarea = document.createElement('textarea');
    textarea.value = content;
    document.body.appendChild(textarea);
    textarea.select();
    try {
        const successful = document.execCommand('copy');
        if (successful) {
            message.success('内容已成功复制到剪贴板');
        } else {
            message.error('复制失败，请手动复制');
        }
    } catch (err) {
        message.error('复制失败，请手动复制');
    }
    document.body.removeChild(textarea);
};
const toggleLike = (script) => {
    script.isLiked = !script.isLiked;
    if (script.isLiked) {
        script.likes++;
    } else {
        script.likes--;
    }
};
onMounted(() => {
    addSession();
    getQuestion();
    initEchars();

});
onBeforeUnmount(() => {
    if (chatInstance.value) {
        chatInstance.value.destroy()
    }
})
</script>
<style scoped>
.h-80 {
    height: 320px;
}

input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
}
</style>